package bTree.LeetCode;

import java.util.Arrays;

public class 最接近的三数之和 {
    public int threeSumClosest(int[] nums, int target) {
        int length = nums.length;
        int closeSum = Integer.MAX_VALUE;
        Arrays.sort(nums);
        for (int i = 0; i < length - 2; i++) {
            int j = i + 1, z = length -1;
            while (j < z) {
                int pathSum = nums[i] + nums[j] + nums[z];
                if(Math.abs(target-pathSum)<Math.abs(closeSum-target)){
                    closeSum=pathSum;
                }
                if (pathSum == target) {
                    return target;
                } else if (pathSum > target) {
                    z--;
                }else {
                    j++;
                }
            }
        }
        return closeSum;
    }
}